<template>
    <div class="white-box">
        <div class="table-mb">
            <el-button type="primary" @click="clickUpdate(1)">添加</el-button>
            <!-- <el-button type="default" plain @click="allDel">批量删除</el-button> -->
        </div>

        <!-- @selection-change="handleAllSelected" -->
        <el-table
            class="table-mb"
            v-loading="loading"
            :data="arr_data"
            :header-cell-style="{ background: '#F5F7FA' }"
            element-loading-background="rgba(255, 255, 255, 0.6)"
        >
            <!-- <el-table-column type="selection" width="55" /> -->
            <el-table-column prop="dc_id" label="ID" width="70"></el-table-column>
            <el-table-column prop="title" label="站点名称" min-width="120"></el-table-column>
            <el-table-column prop="phone" label="联系电话" width="120"></el-table-column>
            <el-table-column prop="weixin" label="微信" width="120"></el-table-column>
            <el-table-column label="站点地址" min-width="180">
                <template #default="{ row }"> {{ row.addr }}{{ row.house }} </template>
            </el-table-column>
            <el-table-column label="支持自提" width="80">
                <template #default="{ row }">
                    <span style="color: #4b93fa">{{ row.is_self == 0 ? "不支持" : "支持" }}</span>
                </template>
            </el-table-column>
            <el-table-column label="物流费/Kg" width="90">
                <template #default="{ row }">
                    <span>{{ row.freight_amount }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="delivery_time" label="送达时间" width="80"></el-table-column>
            <el-table-column label="供货通知时间" width="130">
                <template #default="{ row }">
                    <p>送货: {{ row.sms_delivery }}</p>
                    <p>未送货: {{ row.sms_delivery_warn }}</p>
                </template>
            </el-table-column>
            <el-table-column prop="created_at_label" label="添加时间" width="160"></el-table-column>
            <el-table-column label="状态" width="80" fixed="right">
                <template #default="{ row }">
                    <span style="color: #4b93fa">{{ row.dc_status == 0 ? "已停用" : "已启用" }}</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="166" class-name="operation-nav" fixed="right">
                <template #default="scope">
                    <el-button class="theme-btn" link type="primary" @click="clickUpdate(2, scope.row)">编辑</el-button>
                    <el-button class="theme-btn" link type="primary" @click="clickStatus(scope.row, scope.$index)">
                        {{ scope.row.dc_status == 0 ? "启用" : "停用" }}
                    </el-button>
                    <el-popconfirm title="是否确定删除？" confirm-button-text="确定" cancel-button-text="取消" @confirm="handleDelete(scope.row)">
                        <template #reference>
                            <el-button class="theme-btn" link type="primary">删除</el-button>
                        </template>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-pagination
            background
            v-model:current-page="page"
            v-model:page-size="pageSize"
            :page-sizes="pageSizeNum"
            :total="totalNums"
            layout="total, sizes, prev, pager, next, jumper"
        >
        </el-pagination>

        <!-- 添加/编辑 -->
        <el-drawer
            :title="classType == 1 ? '添加站点' : '编辑站点'"
            v-model="dialogZd"
            direction="rtl"
            size="640px"
            :append-to-body="true"
            :destroy-on-close="true"
            @close="closeAddZd"
        >
            <el-form ref="ruleZdRef" :model="ruleZdForm" :rules="ruleCheckZd" label-width="160px">
                <el-form-item label="站点名称" prop="title">
                    <el-input v-model.trim="ruleZdForm.title" clearable placeholder="请输入站点名称" />
                </el-form-item>
                <el-form-item label="联系电话" prop="tel">
                    <el-input
                        v-model="ruleZdForm.tel"
                        clearable
                        oninput="value=value.replace(/[^\d-]/g,'')"
                        placeholder="请输入联系电话"
                    />
                </el-form-item>
                <el-form-item label="微信号" prop="wxh">
                    <el-input v-model.trim="ruleZdForm.wxh" clearable placeholder="请输入微信号" />
                </el-form-item>
                <el-form-item label="所在地区" prop="area_code">
                    <el-cascader
                        ref="cascaderRef"
                        v-model="ruleZdForm.area_code"
                        :props="props"
                        :options="allArea"
                        clearable
                        placeholder="请选择省市区"
                    />
                </el-form-item>
                <el-form-item label="支持自提" prop="is_self" required>
                    <el-switch
                        v-model="ruleZdForm.is_self"
                        width="72px"
                        size="large"
                        :inactive-value="0"
                        :active-value="1"
                        inline-prompt
                        active-text="支持"
                        inactive-text="不支持"
                    />
                </el-form-item>
                <el-form-item label="详细地址" prop="address">
                    <el-input v-model.trim="ruleZdForm.address" type="textarea" clearable :rows="3" placeholder="请输入详细地址" />
                </el-form-item>
                <el-form-item label="经纬度" prop="lat_lng" required>
                    <el-input
                        v-model.trim="ruleZdForm.lat_lng"
                        readonly
                        :suffix-icon="ArrowRight"
                        placeholder="请选择当前位置的经纬度"
                        clearable
                        @click="clickLatAndLng"
                    >
                    </el-input>
                </el-form-item>
                <el-form-item label="佣金百分比" prop="award_percent">
                    <el-input
                        v-model="ruleZdForm.award_percent"
                        clearable
                        oninput="value=value.replace(/[^\d.]/g,'')"
                        placeholder="请输入佣金百分比"
                    />
                    <span class="input-icon">%</span>
                </el-form-item>
                <el-form-item label="供应商放货费" prop="release_amount">
                    <el-input
                        v-model="ruleZdForm.release_amount"
                        clearable
                        oninput="value=value.replace(/[^\d.]/g,'')"
                        placeholder="请输入供应商放货费"
                    />
                </el-form-item>
                <el-form-item label="员工放货费" prop="staff_release_amount">
                    <el-input
                        v-model="ruleZdForm.staff_release_amount"
                        clearable
                        oninput="value=value.replace(/[^\d.]/g,'')"
                        placeholder="请输入员工放货费"
                    />
                </el-form-item>
                <el-form-item label="送达时间" prop="delivery_time">
                    <el-time-picker v-model="ruleZdForm.delivery_time" format="HH:mm" placeholder="请选择送达时间" @change="changeTimeOne" />
                </el-form-item>
                <el-form-item label="供货送货通知时间" prop="sms_delivery">
                    <el-time-picker v-model="ruleZdForm.sms_delivery" format="HH:mm" placeholder="请选择供货送货通知时间" @change="changeTimeTwo" />
                </el-form-item>
                <el-form-item label="供货未送货通知时间" prop="sms_delivery_warn">
                    <el-time-picker
                        v-model="ruleZdForm.sms_delivery_warn"
                        format="HH:mm"
                        placeholder="请选择供货未送货通知时间"
                        @change="changeTimeThree"
                    />
                </el-form-item>
                <el-form-item label="排序" prop="sort">
                    <el-input v-model.number="ruleZdForm.sort" clearable oninput="value=value.replace(/[^\d]/g,'')" placeholder="请输入排序数字" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="drawer-footer flexs-center">
                    <el-button type="primary" :loading="form_loading" @click="submitZdForm(ruleZdRef)">
                        {{ classType == 1 ? "确认添加" : "确认修改" }}
                    </el-button>
                    <el-button @click="resetZdForm(ruleZdRef)">重置</el-button>
                </div>
            </template>
        </el-drawer>

        <!-- 获取经纬度 -->
        <el-dialog v-model="dialogMap" title="获取经纬度" width="600px" :close-on-click-modal="false" :append-to-body="true" :destroy-on-close="true">
            <div class="p16">
                <div class="task-one">
                    <div class="task-one__item">
                        <span class="task-one__label">地址：</span>
                        <el-input placeholder="输入地址获取经纬度" v-model.trim="addrs" clearable style="width: 280px"></el-input>
                    </div>
                    <div class="task-one__btn">
                        <el-button type="primary" :loading="search_btn" :icon="Search" @click="handleSearch">获取</el-button>
                    </div>
                </div>
                <div id="container"></div>
            </div>
            <template #footer>
                <span class="dialog-footer">
                    <el-button type="primary" @click="confirmMap">确认地址</el-button>
                    <el-button @click="dialogMap = false">取消</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { getCurrentInstance, ref, onMounted, watch, reactive, onBeforeUnmount } from "vue"
import { Search, ArrowRight } from "@element-plus/icons-vue"
import { jsonp } from "vue-jsonp"
import OneLoad from "@mixins/one-load"

const { proxy } = getCurrentInstance()

onMounted(() => {
    getArea()
    getList()
})

// 销毁
onBeforeUnmount(() => {
    map = null
    marker = null
    cascaderRef.value = null
    ruleZdRef.value = null
    // 移除绑定事件
    window.removeEvent = function () {
        qq.maps.event.removeListener(eventDragend)
        eventDragend = null
    }

})

/**
 * minxin列表加载
 */
const { page, pageSizeNum, pageSize, loading, arr_data, totalNums, pubParams, getdata } = OneLoad()

// 切换每页显示条数
watch(pageSize, (val) => {
    page.value = 1
    pubParams(getList)
})
// 跳转第几页
watch(page, (val) => {
    pubParams(getList)
})

function getList() {
    let params = {
        page: page.value,
        limit: pageSize.value,
    }
    getdata("dc/index?title", params)
}

/**
 * 添加/编辑
 * @property {Boolean} dialogZd 添加/编辑弹窗状态
 * @property {Boolean} form_loading 提交按钮状态
 * @property {Number} classType 弹窗类型，1是添加，2是编辑
 * @property {Array} ruleZdRef 表单规则
 * @property {Object} ruleZdForm  表单字段
 * @property {Object} ruleCheckZd  表单提示
 * @property {Function} submitZdForm 提交表单
 * @property {Function} closeAddZd 关闭弹窗
 */
const dialogZd = ref(false)
const form_loading = ref(false)
const classType = ref(1)
const ruleZdRef = ref(null)
const ruleZdForm = reactive({
    id: "",
    title: "",
    tel: "",
    area_code: [],
    address: "",
    wxh: "",
    is_self: 0,
    award_percent: "",
    release_amount: "",
    staff_release_amount: "",
    sort: 100,
    delivery_time: "",
    delivery_time_label: "",
    sms_delivery: "",
    sms_delivery_label: "",
    sms_delivery_warn: "",
    sms_delivery_warn_label: "",
    lat_lng: [],
})
const ruleCheckZd = reactive({
    title: [{ required: true, message: "请输入提货点名称", trigger: "blur" }],
    // tel: [{ required: true, validator: proxy.$util.validPhone, trigger: "blur" }],
    tel: [{ required: true, message: "请输入联系电话", trigger: "blur" }],
    area_code: [{ type: "array", required: true, message: "请选择省市区", trigger: "change" }],
    address: [{ required: true, message: "请输入详细地址", trigger: "blur" }],
    wxh: [{ required: true, message: "请输入微信号", trigger: "blur" }],
    award_percent: [{ required: true, validator: proxy.$util.validNumOrPoint, trigger: "blur" }],
    release_amount: [{ required: true, validator: proxy.$util.validNumOrPoint, trigger: "blur" }],
    staff_release_amount: [{ required: true, validator: proxy.$util.validNumOrPoint, trigger: "blur" }],
    sort: [{ required: true, message: "请输入排序", trigger: "blur" }],
    delivery_time: [{ required: true, message: "请选择送达时间", trigger: "change" }],
    sms_delivery: [{ required: true, message: "请选择供货送货通知时间", trigger: "change" }],
    sms_delivery_warn: [{ required: true, message: "请供货未送货通知时间", trigger: "change" }],
    lat_lng: [{ required: true, type: "array", message: "请选择当前位置的经纬度", trigger: "change" }],
})
const submitZdForm = (formEl) => {
    if (!formEl) return
    formEl.validate((valid, fields) => {
        if (valid) {
            form_loading.value = true
            let areas = cascaderRef.value.getCheckedNodes(false) // 获取级联选择的node
            let data = {
                title: ruleZdForm.title,
                phone: ruleZdForm.tel,
                weixin: ruleZdForm.wxh,
                is_self: ruleZdForm.is_self,
                province_code: ruleZdForm.area_code ? ruleZdForm.area_code[0] : "",
                city_code: ruleZdForm.area_code ? ruleZdForm.area_code[1] : "",
                district_code: ruleZdForm.area_code ? ruleZdForm.area_code[2] : "",
                province: areas[0].pathLabels[0],
                lat: ruleZdForm.lat_lng[0],
                lng: ruleZdForm.lat_lng[1],
                city: areas[0].pathLabels[1],
                district: areas[0].pathLabels[2],
                house: ruleZdForm.address,
                award_percent: ruleZdForm.award_percent,
                release_amount: ruleZdForm.release_amount,
                staff_release_amount: ruleZdForm.staff_release_amount,
                delivery_time: ruleZdForm.delivery_time_label,
                sms_delivery: ruleZdForm.sms_delivery_label,
                sms_delivery_warn: ruleZdForm.sms_delivery_warn_label,
                order_by: ruleZdForm.sort,
            }
            if (classType.value == 2) {
                data.dc_id = ruleZdForm.id
            }
            let url = classType.value == 1 ? "dc/add" : "dc/update"
            proxy.$axios
                .post(url, data)
                .then((res) => {
                    form_loading.value = false
                    if (res.data.code == 0) {
                        dialogZd.value = false
                        proxy.$message({ message: `${classType.value == 1 ? '添加成功！' : '编辑成功！'}`, type: "success" })
                        pubParams(getList)
                    } else {
                        proxy.$message({message:res.data.msg,type:"error"})
                    }
                })
                .catch((err) => {
                    form_loading.value = false
                })
        }
    })
}
const resetZdForm = (formEl) => {
    if (!formEl) return
    formEl.resetFields()
}
const closeAddZd = () => {
    dialogZd.value = false
    resetZdForm(ruleZdRef.value)
}

// 添加/编辑
const clickUpdate = (type, row) => {
    classType.value = type
    dialogZd.value = true
    addrs.value = ""
    type == 2 && getEditDetail(row.dc_id)
}
function getEditDetail(id) {
    proxy.$axios
        .get("dc/update", {
            params: {
                dc_id: id,
            },
        })
        .then((res) => {
            if (res.data.code == 0) {
                let result = res.data.data
                ruleZdForm.id = result.dc_id
                ruleZdForm.title = result.title
                ruleZdForm.address = result.house
                ruleZdForm.tel = result.phone
                ruleZdForm.wxh = result.weixin
                ruleZdForm.award_percent = result.award_percent
                ruleZdForm.is_self = Number(result.is_self)
                ruleZdForm.freight_amount = result.freight_amount
                ruleZdForm.release_amount = result.release_amount
                ruleZdForm.staff_release_amount = result.staff_release_amount
                ruleZdForm.sort = result.order_by
                ruleZdForm.lat_lng = [result.lat, result.lng].map(Number)
                ruleZdForm.area_code = [result.province_code, result.city_code, result.district_code].map(String)

                // 将时分格式化
                let now = new Date()
                let timeOne = result.delivery_time.split(":")
                let delivery_times = new Date(now.getFullYear(), now.getMonth(), now.getDate(), Number(timeOne[0]), Number(timeOne[1]))
                let timeTwo = result.sms_delivery_warn.split(":")
                let sms_delivery_warns = new Date(now.getFullYear(), now.getMonth(), now.getDate(), timeTwo[0], timeTwo[1])
                let timeThree = result.sms_delivery.split(":")
                let sms_deliverys = new Date(now.getFullYear(), now.getMonth(), now.getDate(), timeThree[0], timeThree[1])

                ruleZdForm.delivery_time = delivery_times
                ruleZdForm.sms_delivery_warn = sms_delivery_warns
                ruleZdForm.sms_delivery = sms_deliverys
                ruleZdForm.delivery_time_label = result.delivery_time
                ruleZdForm.sms_delivery_label = result.sms_delivery
                ruleZdForm.sms_delivery_warn_label = result.sms_delivery_warn

                addrs.value = result.province + result.city + result.district + result.house
            } else {
                proxy.$message({message:res.data.msg,type:"error"})
            }
        })
        .catch((err) => {})
}
// 格式化送达时间
const changeTimeOne = (val) => {
    if (val) {
        let times = proxy.$util.formatAtTimes(val)
        ruleZdForm.delivery_time_label = times.substring(0, times.length - 3)
    }
}
// 格式化送达时间
const changeTimeTwo = (val) => {
    if (val) {
        let times = proxy.$util.formatAtTimes(val)
        ruleZdForm.sms_delivery_label = times.substring(0, times.length - 3)
    }
}
// 格式化送达时间
const changeTimeThree = (val) => {
    if (val) {
        let times = proxy.$util.formatAtTimes(val)
        ruleZdForm.sms_delivery_warn_label = times.substring(0, times.length - 3)
    }
}

// 设置站点状态
const clickStatus = (row, index) => {
    proxy.$axios
        .post("dc/status", {
            dc_id: row.dc_id,
            status: row.dc_status == 0 ? 1 : 0,
        })
        .then((res) => {
            if (res.data.code == 0) {
                proxy.$message({ message: "设置成功", type: "success" })
                arr_data.value[index].dc_status = row.dc_status == 0 ? 1 : 0
            } else {
                proxy.$message({message:res.data.msg,type:"error"})
            }
        })
        .catch((err) => {})
}

// 删除单个
const handleDelete = (row) => {
    postDel(row.dc_id)
}
// 删除多个
// const ids = ref([])
// const handleAllSelected = (val) => {
//     let arrs = []
//     for (let i = 0; i < val.length; i++) {
//         arrs.push(val[i].id)
//     }
//     ids.value = arrs
// }
// const allDel = () => {
//     if (ids.value.length == 0) {
//         proxy.$message({ message: "请选择需要删除的数据", type: "warning" })
//         return
//     }
//     postDel(ids.value)
// }
// 删除接口
function postDel(params) {
    proxy.$axios
        .post("dc/delete", {
            dc_id: params,
        })
        .then((res) => {
            if (res.data.code == 0) {
                proxy.$message({ message: '删除成功！', type: "success" })
                pubParams(getList)
            } else {
                proxy.$message({message:res.data.msg,type:"error"})
            }
        })
        .catch((err) => {})
}

/**
 * 腾讯地图-根据地址获取经纬度
 * @param {Boolean} dialogMap 地图弹窗
 * @param {String} locations 经纬度地址
 * @param {String} addrs 搜索字段
 * @param {Object} map Map 构造函数创建地图
 * @param {Function} initMap 初始化地图
 */
var map = null,
    marker = null,
    eventDragend = null
const addrs = ref("")
const locations = ref("")
const search_btn = ref(false)
const dialogMap = ref(false)
const handleSearch = () => {
    if (addrs.value == "") {
        proxy.$message({ message: "请输入详细地址！", type: "warning" })
        return
    }
    search_btn.value = true
    jsonp("https://apis.map.qq.com/ws/geocoder/v1/?address=", {
        output: "jsonp",
        address: addrs.value,
        key: "RIRBZ-LYM6O-Z73WF-S4A5Z-IEUB5-DXFYZ",
    })
        .then((res) => {
            search_btn.value = false
            if (res.status == 0) {
                locations.value = `${res.result.location.lat},${res.result.location.lng}`
                let center = new qq.maps.LatLng(res.result.location.lat, res.result.location.lng)
                map.panTo(center) // 重新设置地图中心点
                initMap(res.result.location.lat, res.result.location.lng)
            } else {
                proxy.$message({ message: res.message, type: "warning" })
            }
        })
        .catch((err) => {
            search_btn.value = false
        })
}
const clickLatAndLng = () => {
    dialogMap.value = true
    setTimeout(() => {
        classType.value == 1 && initMap()
        classType.value == 2 && initMap(ruleZdForm.lat_lng[0], ruleZdForm.lat_lng[1])
    }, 50)
}
const confirmMap = () => {
    dialogMap.value = false
    addrs.value = ""
    ruleZdForm.lat_lng = locations.value.split(",")
}
function initMap(lat = 39.90923, lng = 116.397428) {
    let myLatlng = new qq.maps.LatLng(lat, lng)
    let myOptions = {
        zoom: 17,
        center: myLatlng,
    }
    map = new qq.maps.Map(document.getElementById("container"), myOptions)
    marker = new qq.maps.Marker({
        // 设置标记
        position: myLatlng,
        draggable: true,
        animation: qq.maps.MarkerAnimation.DROP,
        map: map,
    })
    eventDragend = qq.maps.event.addListener(marker, "dragend", function (e) {
        // 监听标记拖动
        let latLng = marker.getPosition()
        map.setCenter(latLng)
        let lats = latLng.lat.toFixed(6)
        let lng = latLng.lng.toFixed(6)
        locations.value = `${lats},${lng}`
    })
}

/**
 * 选择省市区
 * @param {Array} allArea 存放省市区数组
 * @param {Object} cascaderRef 容器ref
 * @param {Function} getArea 请求json
 */
const allArea = ref([])
const cascaderRef = ref(null)
const props = {
    label: "name",
    value: "adcode",
    children: "districts",
}
function getArea() {
    proxy.$axios
        .get("gaode-area.json")
        .then((res) => {
            let result = res.data.districts
            allArea.value = result[0].districts
        })
        .catch((err) => {})
}
</script>
<script>
export default {
    name: "PickUpGoods",
}
</script>

<style lang="less" scoped>
.input-icon {
    margin-left: @margin-sm;
    color: @gray-7;
}

#container {
    width: 100%;
    height: 400px;
}
</style>
